import axios from 'axios'
import {
  Message,
  Loading
} from 'element-ui'
import store from '../store'
import {
  getToken
} from '@/utils/auth'
import qs from 'qs'
import router from '../router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 15000, // 请求超时时间
  showError: true, // 是否显示错误
  withCredentials: true
})

// service.defaults.withCredentials = true
/**
 * 自动遮罩相关参数
 */
const loadingText = '拼命加载中'
var requestCount = 0
var loading = null

/**
 * 显示加载框
 * @param {*} config 配置
 */
function autoShowLoading (config) {
  if (typeof config.showLoading === 'undefined' || config.showLoading) {
    if (!loading) {
      loading = Loading.service({
        target: '.loading-mask',
        lock: true,
        text: config.loadingText || loadingText
      })
    }
  }
  requestCount++
}

/**
 * 隐藏加载框
 */
function autoHideLoading () {
  if (--requestCount <= 0) {
    requestCount = 0
    if (loading) {
      loading.close()
      loading = null
    }
  }
}

// request拦截器
service.interceptors.request.use(config => {
  autoShowLoading(config)

  var token = null
  if (!store.getters.token) {
    var cookieToken = getToken()
    if (cookieToken) {
      store.commit('SET_TOKEN', cookieToken)
      token = cookieToken
    }
  } else {
    token = store.getters.token
  }
  if (token) {
    config.headers.Authorization = `${token}` // 让每个请求携带自定义token 请根据实际情况自行修改
  }

  if (store.getters.currentMenu && store.getters.currentMenu.id) {
    config.headers['X-Menu-Id'] = `${store.getters.currentMenu.id}` // 让每个请求携带自定义token 请根据实际情况自行修改
  }

  if (process.env.VUE_APP_SOURCE_ID) {
    config.headers['X-Source'] = process.env.VUE_APP_SOURCE_ID // 让每个请求携带自定义token 请根据实际情况自行修改
  }

  /**
   * 组装分页信息
   */
  if (config.pageInfo) {
    config.headers['X-Page-Index'] = (config.pageInfo.pageIndex ? config.pageInfo.pageIndex : 1)
    config.headers['X-Page-Size'] = config.pageInfo.pageSize ? config.pageInfo.pageSize : 20
    if (Array.isArray(config.pageInfo.orders) && config.pageInfo.orders.length > 0) {
      config.headers['X-Page-Sort'] = config.pageInfo.orders
    }
  }
  if (!config.dataType) {
    config.dataType = 'json'
  }
  if ((config.method === 'post' || config.method === 'put') && config.dataType !== 'json') {
    if (!config.data) {
      config.data = []
    }
    config.data = qs.stringify(config.data)
  }
  return config
}, error => {
  // Do something with request error
  console.debug(error) // for debug
  Message.closeAll()
  if (error.code === 'ECONNABORTED') {
    Message({
      message: '访问超时啦，请检查您的网络是否正常',
      type: 'error'
    })
  } else {
    Message({
      message: '访问失败啦，网络可能不稳定，请稍后重试',
      type: 'error'
    })
  }
  Promise.reject(error)
  autoHideLoading()
})

// respone拦截器
service.interceptors.response.use(
  async response => {
    autoHideLoading()
    const res = response.data
    console.debug('response', response)
    if (response.config.responseType === 'blob') {
      var reader = new FileReader()
      return await new Promise((resolve, reject) => {
        let blob
        reader.onload = function () {
          try {
            console.log('read', reader)
            var jsonData = JSON.parse(reader.result)
            if (jsonData.status) {
              response.config.showError && jsonData.msg && Message({
                message: jsonData.msg,
                type: 'warning'
              })
            }
            return reject(new Error())
          } catch (error) {
            blob = new Blob([res], { type: res.type })
            console.log('blob', blob)
            return resolve(blob)
          }
        }
        reader.readAsText(res, 'utf-8')
      })
    } else {
      if (res.status && res.status !== 200) {
        if (response.config.showError && res.message) {
          Message({
            message: res.message,
            type: 'warning'
          })
        }
        if (response.config.showError && !res.message) {
          Message.closeAll()
          Message({
            message: '请求失败，请稍后重试',
            type: 'warning'
          })
        }

        return Promise.reject(res)
      }
      return res
    }
  },
  error => {
    autoHideLoading()
    // 400 bad request 401 auth fail 403 forbid 404 not found 500 internal error
    console.debug({
      err: error
    }) // for debug
    if (error.response && error.response.status && error.response.status !== 200) {
      switch (error.response.status) {
        case 400:
          error.message = '错误的请求'
          break
        case 401:
          store.dispatch('FedLogOut')
          error.message = (error.response.data && error.response.data.msg) ? error.response.data.msg : (error.response.data.message ? error.response.data.message : '登录已超时，请重新登录')
          router.replace({
            name: 'login',
            params: {
              lastPath: router.history.current.fullPath
            }
          })
          break
        case 403:
          error.message = error.response.data && error.response.data.message ? `你没有「 ${error.response.data.message} 」的权限` : '未授权请求'
          break
        case 404:
          error.message = '请求的资源不存在'
          break
        case 500:
          error.message = (error.response.data && error.response.data.msg) ? `服务器内部错误:${error.response.data.msg}` : '服务器内部错误'
          break
      }
    } else {
      error.message = '网络请求错误，请检查网络状况稍后重试'
    }
    Message.closeAll()
    Message({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default service
